package io.gitee.itxinmeng.encrypt.spring.boot.autoconfigure;

import cn.hutool.extra.spring.SpringUtil;
import io.gitee.itxinmeng.encrypt.spring.boot.aspect.ReqBodyAdvice;
import io.gitee.itxinmeng.encrypt.spring.boot.aspect.ResBodyAdvice;
import io.gitee.itxinmeng.encrypt.spring.boot.common.encrypt.EncryptMethodFactory;
import io.gitee.itxinmeng.encrypt.spring.boot.common.encrypt.strategy.impl.AesEncryptStrategyImpl;
import io.gitee.itxinmeng.encrypt.spring.boot.common.encrypt.strategy.impl.RsaEncryptStrategyImpl;
import io.gitee.itxinmeng.encrypt.spring.boot.common.encrypt.strategy.impl.SignAndAesEncryptStrategyImpl;
import io.gitee.itxinmeng.encrypt.spring.boot.autoconfigure.properties.EncryptProperties;
import io.gitee.itxinmeng.encrypt.spring.boot.db.AppAuthRepository;
import io.gitee.itxinmeng.encrypt.spring.boot.db.DbUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.Resource;

/**
 * @author mx
 */
@Import({EncryptProperties.class,
        AesEncryptStrategyImpl.class,
        RsaEncryptStrategyImpl.class,
        SignAndAesEncryptStrategyImpl.class,
        ResBodyAdvice.class,
        ReqBodyAdvice.class})
@Configuration
public class MxEncryptAutoConfigure {
    private static final Logger LOGGER = LoggerFactory.getLogger(MxEncryptAutoConfigure.class);
    @Resource
    private EncryptProperties config;

    @Bean(initMethod = "init")
    public AppAuthRepository initDb() {
        LOGGER.info("initDb {}", this);
        if (EncryptMethodFactory.EncryptMethodEnum.SIGN_AND_AES
                .name().equalsIgnoreCase(config.getMethod())) {
            JdbcTemplate jdbcTemplate = SpringUtil.getBean("jdbcTemplate");
            AppAuthRepository repository = new AppAuthRepository(jdbcTemplate, config.getTableName());
            DbUtils.setRepository(repository);
            return repository;
        } else {
            return null;
        }
    }
}
